#!/bin/bash

function ff_cp() {
    file_path=$1
    copy_path=${file_path}"/ff_renamed/"

    if ! [ -d $copy_path ]
    then
        echo "目标文件夹不存在"
        echo "创建目标文件夹..."
        mkdir $copy_path
        echo "创建目标文件夹成功 $copy_path"
    else
        echo "目标文件夹已存在"
    fi

    if [ "$origin_str" = " " ]
    then
        echo "------------------>>>>>> 添加前缀模式 <<<<<<------------------"
        ff_add
    else
        echo "------------------>>>>>> 替换前缀模式 <<<<<<------------------"
        ff_replace
    fi
}

function ff_add() {
    for (( i = 0; i < ${#files_arr[@]}; i++ )); do
        filename=${files_arr[$i]}
        true_filename=(`echo $filename | sed 's/-/[[:space:]]/g'`)

        suffix_str=${true_filename#$origin_str}
        final_name=$replace_str$suffix_str
        echo "$true_filename 修改后的文件名：$final_name"
        cp "$file_path/$true_filename" "$copy_path$final_name"
    done
}

function ff_replace() {
    for (( i = 0; i < ${#files_arr[@]}; i++ )); do
        filename=${files_arr[$i]}
        true_filename=(`echo $filename | sed 's/-/[[:space:]]/g'`)

        if [[ $true_filename == $origin_str* ]]
        then
#            echo "$true_filename 以 $origin_str 为前缀"
            suffix_str=${true_filename#$origin_str}
            final_name=$replace_str$suffix_str
            echo "$true_filename 修改后的文件名：$final_name"
            cp "$file_path/$true_filename" "$copy_path$final_name"
        else
            echo "$true_filename 不以 $origin_str 为前缀"
        fi
    done
}

# -----

file_path=$1
origin_str=$2
replace_str=$3

if [ ${#file_path} -eq 0 ]
then
    echo "非法路径"
    exit
fi

if [ ${#origin_str} -eq 0 ]
then
    echo "请输入需要替换的前缀"
    exit
fi

if [ ${#replace_str} -eq 0 ]
then
    echo "请输入替换后的前缀"
    exit
fi

echo "目标路径：$file_path"
echo "需要替换的前缀：$origin_str"
echo "替换后的前缀：$replace_str"

temp_files_arr=(`ls $file_path | sed 's/[[:space:]]/-/g'`)
temp_num=${#temp_files_arr[@]}
echo "路径内-内容数量（包含文件和文件夹）：$temp_num"

for filename in ${temp_files_arr[@]}; do
    if ! [ -d $file_path/$filename ]
    then
        files_arr+=($filename)
    fi
done

files_num=${#files_arr[@]}
echo "路径内-文件数量：$files_num"

if [ $files_num -eq 0 ]
then
echo "目标文件夹为空"
exit
fi

#temp_length=${#files_num}

ff_cp $file_path

echo ""
echo "操作完成 bye ~"
